<?php

namespace app\admin\controller;

use app\model\CompanyModel;
use app\model\CityModel;
use support\Request;
use support\Response;
use Exception;
use app\model\CardModel;
use app\model\CardItemModel;
use app\model\CardUserModel;
use app\model\CompanyKfModel;

class CompanyController
{
    /**
     * 获取公司列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            
            $query = CompanyModel::query()
                ->leftJoin('city', 'company.city_id', '=', 'city.id')
                ->select('company.*', 'city.name as city_name')
                ->whereNull('company.deleted_at')
                ->orderBy('company.id', 'desc');
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);

                $item['card_total'] = CardModel::where('company_id', $item->id)->count();

                // 卡片数量
                // card_item表没有company_id字段，需要通过card_id关联card表，再根据company_id统计
                $item['card_item_total'] = CardItemModel::whereIn('card_id', function($query) use ($item) {
                    $query->select('id')->from('card')->where('company_id', $item->id);
                })->count();

                // 领取次数
                $item['card_user_total'] = CardUserModel::whereIn('card_id', function($query) use ($item) {
                    $query->select('id')->from('card')->where('company_id', $item->id);
                })->count();
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取公司详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = $request->get('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $company = CompanyModel::query()
                ->leftJoin('city', 'company.city_id', '=', 'city.id')
                ->select('company.*', 'city.name as city_name')
                ->whereNull('company.deleted_at')
                ->where('company.id', $id)
                ->first();

            if (!$company) {
                throw new Exception('公司不存在');
            }

            $company['created_at'] = date('Y-m-d H:i:s', $company->created_at);
            $company['updated_at'] = date('Y-m-d H:i:s', $company->updated_at);

            return json([
                'data' => $company,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取城市列表（用于下拉选择）
     * @param Request $request
     * @return Response
     */
    public function cityList(Request $request): Response
    {
        try {
            $cities = CityModel::query()
                ->where('status', 1)
                ->whereNull('deleted_at')
                ->select('id', 'name')
                ->orderBy('id', 'asc')
                ->get();

            return json([
                'data' => $cities,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 提交/创建公司
     * @param Request $request
     * @return Response
     */
    public function submit(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['name'])) {
                throw new Exception('公司名称不能为空');
            }

            // 验证城市是否存在（如果提供了city_id）
            if (!empty($data['city_id'])) {
                $city = CityModel::where('id', $data['city_id'])
                    ->where('status', 1)
                    ->whereNull('deleted_at')
                    ->first();
                if (!$city) {
                    throw new Exception('选择的城市不存在或已禁用');
                }
            }

            // 验证员工数量
            if (isset($data['person_total']) && $data['person_total'] < 0) {
                throw new Exception('员工数量不能为负数');
            }

            // 验证手机号格式（如果提供了手机号）
            if (!empty($data['master_phone']) && !preg_match('/^1[3-9]\d{9}$/', $data['master_phone'])) {
                throw new Exception('手机号格式不正确');
            }

            // 判断是新建还是编辑
            if (!empty($data['id'])) {
                $company = CompanyModel::whereNull('deleted_at')->find($data['id']);
                if (!$company) {
                    throw new Exception('公司不存在');
                }
            } else {
                $company = new CompanyModel();
            }

            // 赋值字段
            $company->name = $data['name'];
            $company->city_id = $data['city_id'] ?? null;
            $company->person_total = (int)($data['person_total'] ?? 0);
            $company->master_name = $data['master_name'] ?? '';
            $company->master_phone = $data['master_phone'] ?? '';
            $company->address = $data['address'] ?? '';
            $company->remark = $data['remark'] ?? null;
            $company->updated_at = time();
            
            // 新建时设置创建时间
            if (empty($data['id'])) {
                $company->created_at = time();
            }
            
            if (!$company->save()) {
                throw new Exception(empty($data['id']) ? '添加失败' : '更新失败');
            }

            return json([
                'data' => $company,
                'msg' => empty($data['id']) ? '添加成功' : '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除公司（软删除）
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $company = CompanyModel::whereNull('deleted_at')->find($id);
            if (!$company) {
                throw new Exception('公司不存在');
            }

            if (!$company->softDelete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取所有公司列表（不分页）
     * @param Request $request
     * @return Response
     */
    public function all(Request $request): Response
    {
        try {
            $list = CompanyModel::query()
                ->leftJoin('city', 'company.city_id', '=', 'city.id')
                ->select('company.*', 'city.name as city_name')
                ->whereNull('company.deleted_at')
                ->orderBy('company.id', 'desc')
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);
            }

            return json([
                'data' => $list,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取单位客服列表
     * @param Request $request
     * @return Response
     */
    public function kfList(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            
            $query = \app\model\CompanyKfModel::query()
                ->orderBy('id', 'desc');
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);

                // 解析公司IDs并获取公司信息
                $companyIds = [];
                if (!empty($item->company_ids)) {
                    $companyIds = array_filter(explode('@', $item->company_ids));
                }
                
                $item['company_list'] = [];
                if (!empty($companyIds)) {
                    $companies = CompanyModel::whereIn('id', $companyIds)
                        ->whereNull('deleted_at')
                        ->select('id', 'name')
                        ->get();
                    $item['company_list'] = $companies;
                }
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取单位客服详情
     * @param Request $request
     * @return Response
     */
    public function kfDetail(Request $request): Response
    {
        try {
            $id = $request->get('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $kf = \app\model\CompanyKfModel::whereNull('deleted_at')
                ->where('id', $id)
                ->first();

            if (!$kf) {
                throw new Exception('客服记录不存在');
            }

            $kf['created_at'] = date('Y-m-d H:i:s', $kf->created_at);
            $kf['updated_at'] = date('Y-m-d H:i:s', $kf->updated_at);

            // 解析公司IDs并获取公司信息
            $companyIds = [];
            if (!empty($kf->company_ids)) {
                $companyIds = array_filter(explode('@', $kf->company_ids));
            }
            
            $kf['company_list'] = [];
            if (!empty($companyIds)) {
                $companies = CompanyModel::whereIn('id', $companyIds)
                    ->whereNull('deleted_at')
                    ->select('id', 'name')
                    ->get();
                $kf['company_list'] = $companies;
            }

            return json([
                'data' => $kf,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 提交/创建单位客服
     * @param Request $request
     * @return Response
     */
    public function kfSubmit(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['realname'])) {
                throw new Exception('客服姓名不能为空');
            }

            if (empty($data['phone'])) {
                throw new Exception('客服电话不能为空');
            }

            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $data['phone'])) {
                throw new Exception('手机号格式不正确');
            }

            // 验证公司IDs格式（如果提供了）
            if (!empty($data['company_ids'])) {
                if (!is_array($data['company_ids'])) {
                    throw new Exception('公司ID格式错误');
                }
                
                // 验证公司是否存在
                $companyIds = array_filter($data['company_ids']);
                if (!empty($companyIds)) {
                    $existingCompanies = CompanyModel::whereIn('id', $companyIds)
                        ->whereNull('deleted_at')
                        ->count();
                    if ($existingCompanies != count($companyIds)) {
                        throw new Exception('部分公司不存在');
                    }
                }
            }

            // 判断是新建还是编辑
            if (!empty($data['id'])) {
                $kf = CompanyKfModel::find($data['id']);
                if (!$kf) {
                    throw new Exception('客服记录不存在');
                }
            } else {
                $kf = new CompanyKfModel();
            }

            // 处理公司IDs
            $companyIds = [];
            if (!empty($data['company_ids']) && is_array($data['company_ids'])) {
                $companyIds = array_filter($data['company_ids']);
            }
            $companyIdsStr = '@' . implode('@', $companyIds) . '@';

            // 赋值字段
            $kf->realname = $data['realname'];
            $kf->phone = $data['phone'];
            $kf->company_ids = $companyIdsStr;
            $kf->status = (int)($data['status'] ?? 1);
            $kf->updated_at = time();
            
            // 新建时设置创建时间
            if (empty($data['id'])) {
                $kf->created_at = time();
            }
            
            if (!$kf->save()) {
                throw new Exception(empty($data['id']) ? '添加失败' : '更新失败');
            }

            return json([
                'data' => $kf,
                'msg' => empty($data['id']) ? '添加成功' : '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除单位客服（软删除）
     * @param Request $request
     * @return Response
     */
    public function kfDelete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $kf = \app\model\CompanyKfModel::whereNull('deleted_at')->find($id);
            if (!$kf) {
                throw new Exception('客服记录不存在');
            }

            if (!$kf->softDelete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 为指定公司分配客服
     * @param Request $request
     * @return Response
     */
    public function assignKf(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['company_id'])) {
                throw new Exception('公司ID不能为空');
            }

            if (empty($data['kf_id'])) {
                throw new Exception('客服ID不能为空');
            }

            // 验证公司是否存在
            $company = CompanyModel::whereNull('deleted_at')->find($data['company_id']);
            if (!$company) {
                throw new Exception('公司不存在');
            }

            // 验证客服是否存在
            $kf = \app\model\CompanyKfModel::whereNull('deleted_at')->find($data['kf_id']);
            if (!$kf) {
                throw new Exception('客服记录不存在');
            }

            // 解析当前公司IDs
            $companyIds = [];
            if (!empty($kf->company_ids)) {
                $companyIds = array_filter(explode('@', $kf->company_ids));
            }

            // 检查是否已经分配
            if (in_array($data['company_id'], $companyIds)) {
                throw new Exception('该公司已分配给该客服');
            }

            // 添加公司ID
            $companyIds[] = $data['company_id'];
            $companyIdsStr = '@' . implode('@', $companyIds) . '@';

            $kf->company_ids = $companyIdsStr;
            $kf->updated_at = time();
            
            if (!$kf->save()) {
                throw new Exception('分配失败');
            }

            return json([
                'data' => null,
                'msg' => '分配成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
} 